package atguigu.urlconn;

import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpTest {

    public static void main(String[] args) {

        String urlStr = "http://localhost:8001/LIMS-Server/MPLM_Service_Gateway/TokenGenerator/getToken";
        try {
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
            httpConn.setDoOutput(true); // 允许向url写数据，相当于传递参数，或上传文件
            httpConn.setDoInput(true);  // 允许从url读数据，接收返回的数据
            httpConn.setUseCaches(false);// 设置无缓存

            // 表头参数
//            httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//设置参数类型是json格式
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("__TokenAuthorization_UserName_", "chenbo16");
            httpConn.setRequestProperty("__TokenAuthorization_Function_", "func1");
            httpConn.setRequestMethod("POST");

            // 真正的连接
            httpConn.connect();

            // 向url传递参数
            String parameterData = "username=nickhuang&blog=http://www.cnblogs.com/nick-huang/";
            OutputStream outputStream = httpConn.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(parameterData);

            // 获取返回的数据
            InputStream inputStream = httpConn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            String result = new String(baos.toByteArray(), "utf-8");
            System.out.println(result);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
